package com.hoshiicloud.payment.service.impl;

import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.payment.feign.DownloadService;
import com.hoshiicloud.payment.service.CertificateService;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @program: hoshiicloud
 * @description: 证书服务实现类
 * @author: Mr.wu
 * @create: 2019-06-06 09:57
 **/
@Service
@Slf4j
public class CertificateServiceImpl implements CertificateService {

    @Autowired
    private DownloadService downloadService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @param bucketName
     * @param objectKey
     * @return java.io.InputStream
     * @author: Mr.wu
     * @descripton: 根据存储空间名称和对象名称获取证书文件输入流
     * @date: 10:04 2019/6/6
     */
    @Override
    public InputStream getCert(String bucketName, String objectKey) throws Exception {
        /**
         * 首先去redis获取文件的base64字符串，如果没有获取到则调用文件服务下载文件,并转为base64字符串保存到redis
         */
        Object file = redisTemplate.opsForValue().get(objectKey);
        byte[] fileByte = null;
        InputStream inputStream = null;
        if (file == null || 1 == 1) {
            feign.Response result = downloadService.fileDownload(bucketName, objectKey);
            if (result != null) {
                fileByte = IOUtils.toByteArray(result.body().asInputStream());
                redisTemplate.opsForValue().set(objectKey, Base64.getEncoder().encode(fileByte));
                inputStream = result.body().asInputStream();
            } else {
                throw new ServiceException("获取证书异常");
            }
        } else {
            fileByte = file.toString().getBytes();
            inputStream = new ByteArrayInputStream(fileByte);
        }

        return inputStream;
    }
}
